package ua.kharkov.khpi.tarasenko.bach.web.command.admin;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.LocalizedResourceManager;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.user.Role;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.user.UserDAO;
import ua.kharkov.khpi.tarasenko.bach.dao.core.user.UserDTO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to unban user.
 * 
 * @author oleksandr
 * 
 */
public class UnbanUserCommand extends Command {
	private static final Logger log = Logger.getLogger(UnbanUserCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		String forward = Constant.COMMAND_SHOW_USERS_LIST;
		String errorMessage = null;

		String userIdString = request.getParameter(Constant.ATTRIBUTE_USER_ID);
		if (log.isTraceEnabled()) {
			log.trace("Got parameter from request" + Constant.ATTRIBUTE_USER_ID
					+ "=" + userIdString);
		}

		// Create LocalizedResourceManager to get localized error messages
		LocalizedResourceManager LRManager = getLocalizedResourceManager(request);

		if ((userIdString == null) || (userIdString.isEmpty())) {

			errorMessage = LRManager
					.getMessage("error_message.user_id_not_specified");
		} else {
			int userId = Integer.valueOf(userIdString);
			UserDTO userDTO = new UserDTO();
			userDTO.setId(userId);
			userDTO.setRole(Role.USER);

			Connection conn = null;
			try {
				conn = ConnectionManager.getConnection();
				UserDAO userDAO = DAOFactory.getDAOFactory(
						DAOFactory.DAO_TYPE.MYSQL).getUserDAO(conn);

				int rowsUpdated = userDAO.updateUserRole(userDTO);
				if (rowsUpdated != 1) {
					errorMessage = LRManager
							.getMessage("error_message.user_id_not_found")
							+ userId;
				} else {

					DBUtils.commitAndClose(conn);
				}
			} catch (EShopException e) {
				DBUtils.rollBackAndClose(conn);
				throw e;
			} finally {
				if (conn != null) {
					DBUtils.close(conn);
				}
			}

		}

		if (errorMessage != null) {
			forward = processError(request, errorMessage);
		}

		return forward;
	}
}